package com.shigu.works.service;

import com.opentae.data.mall.beans.RolePermission;
import com.opentae.data.mall.beans.UserRole;
import com.opentae.data.mall.interfaces.ManagerPermissionMapper;
import com.opentae.data.mall.interfaces.ManagerRoleMapper;
import com.shigu.admin.manager.common.PermissionListener;
import com.shigu.admin.manager.vo.Nav;
import com.shigu.component.enums.SessionEnum;
import com.shigu.component.shiro.AuthorityUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Mr.赵
 * created on 2018/12/12
 */
@Service
public class WebUserLoginService {

    @Autowired
    ManagerRoleMapper managerRoleMapper;

    @Autowired
    ManagerPermissionMapper managerPermissionMapper;

    @Autowired
    PermissionListener permissionListener;

    List<String> sortList = new ArrayList<String>(
                            Arrays.asList("商城","系统设置"));

    /**
     * 查出菜单
     * @return
     */
    public List<Nav> selMyMenus(){
        Session session = SecurityUtils.getSubject().getSession();
        AuthorityUser authUser = (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        List<UserRole> roles=managerRoleMapper.selRoleNamesByuserIds(authUser.getUserId().toString());
        List<RolePermission> allPermissions=new ArrayList<>();
        for(UserRole ur:roles){
            allPermissions.addAll(managerPermissionMapper.selPermissiontagsByroleTag(ur.getRoleTag()));
        }
        Map<Long, Nav> map=new HashMap<>();
        List<Nav> navs=new ArrayList<>();
        for(RolePermission p:allPermissions){
            Nav n=new Nav();
            n.setNavId(p.getPermissionId());
            n.setTitle(p.getPermissionComment());
            n.setHref(permissionListener.getUrlByPermission(p.getPermissionTag()));
            if (map.get(p.getPermissionId()) != null) {
                continue;
            }
            map.put(p.getPermissionId(),n);
            navs.add(n);
        }
        for(RolePermission p:allPermissions){
            if (p.getParentPid() == null) {
                continue;
            }
            Nav father=map.get(p.getParentPid());
            Nav son=map.get(p.getPermissionId());
            father.addChildren(son);
            navs.remove(son);
        }

        Collections.sort(navs, new Comparator<Nav>() {
           public int compare(Nav a, Nav b) {
                               Integer v1 = sortList.indexOf(a.getTitle());
                               Integer v2 = sortList.indexOf(b.getTitle());
                               return Integer.compare(v1, v2);
                            }
         });
        return navs;
    }
}
